package com.csdj.web.filter;

import com.csdj.entity.Employee;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * packageName com.csdj.web.filter
 *
 * @author winver
 * @version 1.0
 * @className LoginFilter
 * @date 2024/11/28
 * @description TODO
 */
//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        //强制转换reqeuest对象

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //1. 判断地址
        StringBuffer url = req.getRequestURL();
        System.out.println("url" + url);
        String uri = req.getRequestURI();
        System.out.println("uri:" + uri);
        //获取请求时requets头部信息 【隐藏信息】
        String userAgent = req.getHeader("user-agent");
        System.out.println("userAgent:" + userAgent);


        // 放行集合
        List<String> pathList = Arrays.asList("/login", "/login.jsp", "/ajax.jsp","myAjax");
        boolean isFilter = false;
        for (int i = 0; i < pathList.size(); i++) {
            if (uri.endsWith(pathList.get(i))) {
                isFilter = true;
                break;
            }
        }
        if (isFilter) {
            filterChain.doFilter(req, resp);
        } else {
            //2. 是否登录过  会话中是否有用户信息
            Employee employee = (Employee) req.getSession().getAttribute("employee");
            if (employee != null) {
                filterChain.doFilter(req, resp);
            } else {
                //未登录，跳转到登录界面
                resp.sendRedirect("/login.jsp");
            }
        }


    }
}
